/**
 * 
 */
package info.niwota.commons.web;

import java.lang.reflect.Method;

import org.json.JSONObject;

import android.net.Uri;

/**
 * 
 * @author qiangli
 * 
 */
public class AjaxHanlder {

	public AjaxHanlder() {
	}

	public Object handle(String name, String method, JSONObject data, Uri uri) throws Exception {
		final Object obj = AjaxRegistry.getInstance().get(name);
		final Class<?> c = obj.getClass();
		
		Class<?>[] types = null;
		Object[] args = null;
		// (data, uri)
		try {
			types = new Class[] { JSONObject.class, Uri.class };
			args = new Object[] { data, uri };
			Method m = c.getDeclaredMethod(method, types);
			return m.invoke(obj, args);
		} catch (NoSuchMethodException e) {
			//
		} catch (Exception e) {
			throw e;
		}
		// (data)
		try {
			types = new Class[] { JSONObject.class };
			args = new Object[] { data };
			Method m = c.getDeclaredMethod(method, types);
			return m.invoke(obj, args);
		} catch (NoSuchMethodException e) {
			//
		} catch (Exception e) {
			throw e;
		}
		// no-arg ()
		try {
			Method m = c.getDeclaredMethod(method, types);
			return m.invoke(obj, args);
		} catch (NoSuchMethodException e) {
			//
		} catch (Exception e) {
			throw e;
		}
		//no method found
		return new NoSuchMethodException(method + " not declared in " + c);
	}
}
